﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics.Eventing.Reader;
using System.IO;


namespace DisableContextMenuItems
{
    public partial class Form1 : Form
    {
        private int recordCount = 1;
        private DateTime lastTimeCreated = DateTime.MinValue;
        private string lastPropValue6 = string.Empty;

        public Form1()
        {
            InitializeComponent();

            dataGridView1.AutoGenerateColumns = false;
            comboBox1.Items.Add("删除");//
            comboBox1.Items.Add("新增");
            comboBox1.Items.Add("改名");
            dataGridView1.Columns.Add("序号", "序号");
            dataGridView1.Columns.Add("操作者", "操作者");
            dataGridView1.Columns.Add("文件夹路径", "文件夹路径");
            dataGridView1.Columns.Add("操作", "操作");
            dataGridView1.Columns.Add("日志创建时间", "日志创建时间");
        }

        
        

        private void HandleOperations()
        {
            string route = textBox1.Text.ToString();

            DateTime startTime = dateTimePicker1.Value;
            DateTime endTime = dateTimePicker2.Value;

            string selectedText = comboBox1.Text;
            string code = GetOperationCode(selectedText);

            List<string[]> logData = new List<string[]>();

            string query = $"*[System/EventID={4663}] and *[System[TimeCreated[@SystemTime >= '{startTime.ToUniversalTime():yyyy-MM-ddTHH:mm:ss.fffZ}'] " +
                           $"and TimeCreated[@SystemTime <= '{endTime.ToUniversalTime():yyyy-MM-ddTHH:mm:ss.fffZ}']]]";

            EventLogQuery eventLogQuery = new EventLogQuery("Security", PathType.LogName, query);
            EventLogReader eventLogReader = new EventLogReader(eventLogQuery);

            MessageBox.Show("正在进行查询，请稍候...");

            for (EventRecord eventRecord = eventLogReader.ReadEvent(); eventRecord != null; eventRecord = eventLogReader.ReadEvent())
            {
                if (ShouldSkipEvent(eventRecord, route, code)) continue;

                string[] logEntry = { recordCount.ToString(), eventRecord.Properties[1].Value.ToString(),
                      eventRecord.Properties[6].Value.ToString(), selectedText,
                      eventRecord.TimeCreated.Value.ToString() };
                string parentRoute = Path.GetDirectoryName(eventRecord.Properties[6].Value.ToString());

                // Check if the operation is "改名" and the event contains "%%1537"
                if (selectedText == "改名")
                {
                    DateTime renameTime = eventRecord.TimeCreated.Value;

                    // Perform a second query in the parent route for "%%4417"
                    string secondQuery = $"*[System/EventID={4663}] and *[System[TimeCreated[@SystemTime >= '{renameTime.AddSeconds(-1).ToUniversalTime():yyyy-MM-ddTHH:mm:ss.fffZ}'] " +
                     $"and TimeCreated[@SystemTime <= '{renameTime.AddSeconds(1).ToUniversalTime():yyyy-MM-ddTHH:mm:ss.fffZ}']]]";
                    // $" " +
                    // $"and EventData[@Name='ObjectName'] and EventData='{parentRoute}']]";

                    EventLogQuery secondEventLogQuery = new EventLogQuery("Security", PathType.LogName, secondQuery);
                    EventLogReader secondEventLogReader = new EventLogReader(secondEventLogQuery);
                    bool relatedEventFound = false;

                    for (EventRecord secondEventRecord = secondEventLogReader.ReadEvent(); secondEventRecord != null; secondEventRecord = secondEventLogReader.ReadEvent())
                    {
                        if (secondEventRecord.Properties[6].Value.ToString() == parentRoute && (
                            secondEventRecord.Properties[8].Value.ToString().Contains("%%4417") || secondEventRecord.Properties[8].Value.ToString().Contains("%%4418")))
                        {
                            relatedEventFound = true;
                            break;
                        }
                    }
                    if (relatedEventFound)
                    {
                        recordCount++;

                        logData.Add(logEntry); // Add the log entry from the first query
                    }
                }
                if (selectedText == "删除")
                {
                    DateTime renameTime = eventRecord.TimeCreated.Value;

                    // Perform a second query in the parent route for "%%4417"
                    string secondQuery = $"*[System/EventID={4663}] and *[System[TimeCreated[@SystemTime >= '{renameTime.AddSeconds(-1).ToUniversalTime():yyyy-MM-ddTHH:mm:ss.fffZ}'] " +
                     $"and TimeCreated[@SystemTime <= '{renameTime.AddSeconds(1).ToUniversalTime():yyyy-MM-ddTHH:mm:ss.fffZ}']]]";

                    EventLogQuery secondEventLogQuery = new EventLogQuery("Security", PathType.LogName, secondQuery);
                    EventLogReader secondEventLogReader = new EventLogReader(secondEventLogQuery);
                    bool relatedEventFound = false;
                    for (EventRecord secondEventRecord = secondEventLogReader.ReadEvent(); secondEventRecord != null; secondEventRecord = secondEventLogReader.ReadEvent())
                    {
                        if (secondEventRecord.Properties[6].Value.ToString() == parentRoute && (
                            secondEventRecord.Properties[8].Value.ToString().Contains("%%4417") || secondEventRecord.Properties[8].Value.ToString().Contains("%%4418")))
                        {
                            relatedEventFound = true;
                            break;
                        }
                    }

                    if (!relatedEventFound)
                    {
                        recordCount++;

                        logData.Add(logEntry); // Add the log entry from the first query
                    }
                }
                if (selectedText == "新增")
                {
                    recordCount++;

                    logData.Add(logEntry);
                }



                lastTimeCreated = eventRecord.TimeCreated.Value;
                lastPropValue6 = eventRecord.Properties[6].Value.ToString();
            }

            DisplayLogData(logData);
        }

        private bool ShouldSkipEvent(EventRecord eventRecord, string route, string code)        //如果查询到的日志名中包含TMP则跳过
        {
            if (eventRecord.Properties[6].Value.ToString().IndexOf("TMP", StringComparison.OrdinalIgnoreCase) >= 0)
                return true;

            return !eventRecord.Properties[6].Value.ToString().Contains(route) ||
                       !eventRecord.Properties[8].Value.ToString().Contains(code) ||
                   (!IsFirstRecord() && (eventRecord.TimeCreated.Value - lastTimeCreated).TotalSeconds < 1 &&
                   eventRecord.Properties[6].Value.ToString() == lastPropValue6);
        }
        private bool p_ShouldSkipEvent(EventRecord eventRecord, string route, string code)        //如果查询到的日志名中包含TMP则跳过
        {
            if (eventRecord.Properties[6].Value.ToString().IndexOf("TMP", StringComparison.OrdinalIgnoreCase) >= 0)
                return true;

            return !(eventRecord.Properties[6].Value.ToString() == route) ||
                       !eventRecord.Properties[8].Value.ToString().Contains(code) ||
                   (!IsFirstRecord() && (eventRecord.TimeCreated.Value - lastTimeCreated).TotalSeconds < 1 &&
                   eventRecord.Properties[6].Value.ToString() == lastPropValue6);
        }

        private bool IsFirstRecord()
        {
            return recordCount == 0;
        }

        private void DisplayLogData(List<string[]> logData)
        {
            if (logData.Count > 0)
            {
                foreach (string[] data in logData)
                {
                    dataGridView1.Rows.Add(data);
                }
                dataGridView1.Visible = true;
            }
            else
            {
                MessageBox.Show("未查询到相关日志。");
            }
        }

        private string GetOperationCode(string selectedText)
        {
            switch (selectedText)
            {
                case "删除":
                    return "%%1537";
                case "新增":
                    return "%%4417";
                default:
                    return "%%1537";
            }
        }


      
        private void pictureBox2_Click(object sender, EventArgs e)
        {
            pictureBox2.Click += pictureBox2_Click;
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            string foldPath = "";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                foldPath = dialog.SelectedPath;
                //foldPath = dialog.SelectedPath + @"\";
                //string parentDirectory = Path.GetDirectoryName(foldPath_test);

            }
            textBox1.Text = foldPath;
        }
      
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            HandleOperations();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void dateTimePicker1_ValueChanged_1(object sender, EventArgs e)
        {
            dateTimePicker1.Format = DateTimePickerFormat.Custom;
            dateTimePicker1.CustomFormat = "yyyy-MM-dd HH:mm";
        }

        private void dateTimePicker2_ValueChanged_1(object sender, EventArgs e)
        {
            dateTimePicker2.Format = DateTimePickerFormat.Custom;
            dateTimePicker2.CustomFormat = "yyyy-MM-dd HH:mm";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Hide();
            frmMain f = new frmMain();
            f.Show();
        }
    }
}
